import React from 'react'
import { Redirect } from 'react-router-dom'
import { Form, Icon, Input, Button,message } from 'antd';
import './login.less'
import logo from '../../images/logo.png';

import { reqLogin } from '../../api'
import memoryUtils from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'

class Login extends React.Component {

    handleSubmit = (event) => {
        // 阻止事件的默认行为
        event.preventDefault()
        this.props.form.validateFields(async (err, values) => {
            if (!err) {
                //   console.log('成功 ', values);
                const { username, password } = values
                const response = await reqLogin()
                if (username === response.data.data.user.username && password === response.data.data.user.password) {
                    message.success('登录成功')
                    // 将用户登录的信息保存起来
                    const userInfo = response.data.data.user;
                    memoryUtils.user = userInfo
                    storageUtils.saveUser(userInfo)

                    this.props.history.replace('/')
                    
                } else {
                    alert('登录失败')
                }

                // reqLogin().then(res =>{
                //     // console.log(username);
                //     // console.log(res.data.data.user[0].username);

                //     if(username === res.data.data.user[0].username && password === res.data.data.user[0].password){
                //         this.props.history.replace('/')
                //     }
                // })

            } else {
                console.log('失败');
            }
        });

        // const form = this.props.form
        // const value = form.getFieldsValue()
        // console.log(value);
    }

    // 对密码进行自定义验证的方法
    validatorPwd = (rule, value, callback) => {
        if (!value) {
            callback('请输入密码')
        } else if (value.length < 4) {
            callback('密码长度小于4位')
        } else if (value.length > 12) {
            callback('密码长度大于12位')
        } else if (!/^[a-zA-Z0-9]+$/.test(value)) {
            callback('密码字母数字下划线组成')
        } else {
            callback()  //验证通过
        }
    }

    render() {
        const { getFieldDecorator } = this.props.form;

        // 判断是否已经登陆
        const user = storageUtils.getUser()
        if(user.username){
            return <Redirect to='/'></Redirect>
        }
        
        return (
            // <div style={{width: '100%',height: '100%',background: "red url('../../images/yuantiao.jpg')"}} className='login'>
            <div className='login'>

                <header className='header'>
                    <img src={logo} alt="logo" />
                    <h1>React项目</h1>

                </header>
                <section className='content'>
                    <h2>用户登录</h2>

                    <Form onSubmit={this.handleSubmit} className="login-form">
                        <Form.Item>
                            {
                                getFieldDecorator('username', {
                                    // 声明式验证
                                    rules: [
                                        { required: true, whitespace: true, message: 'Please input your username!' },
                                        { min: 4, message: '至少4位' },
                                        { max: 12, message: '最多12位' },
                                        { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名必须是字母数字下划线组成' }
                                    ],
                                    initialValue: 'tom12' //默认输入值
                                })(
                                    <Input
                                        prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                        placeholder="用户名"
                                    />,
                                )
                            }

                        </Form.Item>
                        <Form.Item>
                            {
                                // 自定义验证
                                getFieldDecorator('password', {
                                    rules: [
                                        { validator: this.validatorPwd }
                                    ]
                                })(
                                    <Input
                                        prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                        type="password"
                                        placeholder="密码"
                                    />
                                )
                            }

                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" className="login-form-button">登录</Button>
                        </Form.Item>
                    </Form>

                </section>

            </div>
        )
    }
}

// 1、高阶函数 ：create()
// 2、高阶组件

// 包装Form组件，生成一个新的组件Form(Login)
const WrapLogin = Form.create()(Login)

export default WrapLogin
